<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <div class="title">项 目 登 录</div>
      </div>
      <!-- <span class="svg-container">
        <svg-icon icon-class="user" />
      </span> -->
      <el-form-item prop="username">
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="账号"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <!-- <span class="svg-container">
        <svg-icon icon-class="password" />
      </span> -->
      <el-tooltip
        v-model="capsTooltip"
        content="Caps lock is On"
        placement="right"
        manual
      >
        <el-form-item prop="password">
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="密码"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
      </el-tooltip>
      <!-- 随机验证码 -->
      <el-form-item prop="verifycode" style="line-height: 0px">
        <el-input
          v-model="loginForm.verifycode"
          ref="verifycode"
          @keyup.enter.native="handleLogin"
          placeholder="验证码"
          class="identifyinput"
          style="width: 230px"
        ></el-input>
        <div class="identifybox" @click="refreshCode">
          <sidentify :identifyCode="identifyCode"></sidentify>
        </div>
        <!-- <div class="identifybox">
          <el-button @click="refreshCode" type='text' class='textbtn' style="color:#fff; padding:0px 0px">
          </el-button>
        </div> -->
      </el-form-item>

      <el-button
        class="submit_btn"
        :loading="loading"
        type="primary"
        @click="handleLogin"
      >
        <span style="letter-spacing: 4px"> 登 录 </span>
      </el-button>

      <!-- 其他方式登录 -->
      <!-- <div style="position:relative">
        <el-button class="thirdparty-button" type="primary" @click="showDialog=true">
          Or connect with
        </el-button>
      </div> -->
    </el-form>

    <!-- 提示 -->
    <!-- <el-dialog title="Or connect with" :visible.sync="showDialog">
      Can not be simulated on local, so please combine you own business simulation! ! !
      <br>
      <br>
      <br>
      <social-sign />
    </el-dialog> -->
  </div>
</template>

<script>
// import { validUsername } from '@/utils/validate'
// import SocialSign from './components/SocialSignin'
import sidentify from "./sidentify";
// import { searchHomeData} from '@/api/home'
export default {
  name: "Login",
  components: { sidentify },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("用户名不能为空"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能少于6位"));
      } else {
        callback();
      }
    };
    // 验证码自定义验证规则
    const validateVerifycode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else if (value !== this.identifyCode) {
        console.log("验证码:", value);
        callback(new Error("验证码不正确!"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "xiaoyi",
        password: "123456",
        verifycode: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        verifycode: [
          { required: true, trigger: "blur", validator: validateVerifycode },
        ],
      },
      passwordType: "password",
      identifyCodes: "1234567890", //验证码的数字库
      identifyCode: "", // 验证码组件传值
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
    };
  },
  methods: {
    //验证码----start
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
      }
      // console.log("this.identifyCode:", this.identifyCode);
    },
    //验证码----end

    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/projectLogin", this.loginForm)
            .then((res) => {
              this.$message.success("登录成功");
              console.log("登录成功");
              this.$router.push({
                path: this.redirect || "/project/projectAdmin",
                query: this.otherQuery,
              });
              this.loading = false;
            })
            .catch(() => {
              console.log("出错了");
              this.$message.error("登录名或密码错误！");
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
    this.refreshCode(); //初始化验证码
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    } else if (this.loginForm.verifycode === "") {
      this.$refs.verifycode.focus();
    }

    // 验证码初始化
    this.identifyCode = "";
    this.makeCode(this.identifyCodes, 4);
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
};
</script>

<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    input {
      background: transparent;
      border-color: #4fa5ff;
      height: 47px;
      color: #5ac1fe;
      &::-webkit-input-placeholder {
        /* placeholder颜色 */
        color: #5ac1fe;
        /* placeholder字体大小 */
        // font-size: 12px;
      }
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background: #172056 url("../../assets/img/userLogin.jpg") no-repeat;
  background-size: 100% 100%;
  .login-form {
    position: fixed;
    width: 484px;
    height: 427px;
    max-width: 100%;
    top: 280px;
    right: 200px;
    // top: 30%;
    // right: 10%;
    background: url("../../assets/img/userLoginInfoBorder.png") no-repeat;
    background-size: 100% 100%;
    padding: 36px 56px;
    border-radius: 16px;
    overflow: hidden;
    .identifybox {
      display: inline-block;
      position: relative;
      top: 4px;
      left: 20px;
      background: #ffffff;
      border: 1px solid #4fa5ff;
      border-radius: 6px;
      height: 47px;
    }
    .submit_btn {
      width: 100%;
      height: 48px;
      border-radius: 24px;
      background: linear-gradient(90deg, #006ae1, #16b7ff);
      box-shadow: 0px 7px 10px 0px rgb(0 0 0 / 26%);
      font-size: 26px;
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: #0ba5ff;
      // margin: 0px auto 40px auto;
      text-align: center;
      // font-weight: bold;
      margin-bottom: 30px;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
